<template>
  <common-search v-model="query" :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" :formItems="formItems" @search="search" @reset="reset"></common-search>
  <my-alert @onClearSelected="onClearSelected" :selectedRowKeys="selectedRowKeys"></my-alert>
  <div style="margin-bottom: 10px">
    <a-button type="primary" @click="handleOpen">新增用户</a-button>
  </div>
  <common-table
    :columns="columns"
    :dataSource="dataList"
    v-model:localPagination="page"
    @paginationChange="onPageChange"
    :slots="['action','status']"
    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    v-model:loading="loading"
    :rowKey="(record) => record.id"
    :scroll="{ x: 'max-content'}"
    >
    <template #status="{ record }">
      <span>{{record.status === 1 ? '正常' : '冻结'}}</span>
    </template>
    <template #action="{ record }">
      <more-btn-container>
        <a @click="handleOpenE(record)">编辑</a>
        <a @click="detail(record)">详情</a>
        <a @click="updatePassword(record)">密码</a>
          <a-popconfirm
              :title="record.status === 1 ? '是否要冻结该账号? ':'是否要解冻该账号?'"
              ok-text="是"
              cancel-text="否"
              @confirm="freeze(record)"
              @cancel="cancel"
              :modulePerm="['user:freeze']"
          >
            <a>{{record.status === 1 ? '冻结' : '解冻'}}</a>
          </a-popconfirm>
          <a-popconfirm
              :modulePerm="['user:delete']"
              title="是否要删除?"
              ok-text="是"
              cancel-text="否"
              @confirm="delOne(record)"
              @cancel="cancel"
          >
            <a >删除</a>
          </a-popconfirm>
<!--        <a @click="agent(record)">代理人</a>-->
      </more-btn-container>
    </template>
  </common-table>
  <add-user-drawer :openA="openA" @handleClose="handleClose"></add-user-drawer>
  <edit-user-drawer v-if="openE" :showDetail="showDetail" :openE="openE" :item="item" @handleClose="handleCloseE"></edit-user-drawer>
  <change-password-modal v-if="openPassword" :openPassword="openPassword" :username="username" @close="handleCancelPassword"/>
</template>
<script setup>
import commonSearch from "@/components/commonSearch/index.vue";
import commonTable from "@/components/commonTable/index.vue";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import {deleteOneUser, frozenBatch, getUserList, queryUserSync} from "@/api/system/user.js";
import {reactive, ref} from "vue";
import AddUserDrawer from "@/components/drawer/addUserDrawer.vue";
import MoreBtnContainer from "@/components/moreBtnContainer/index.vue";
import {message} from "ant-design-vue";
import EditUserDrawer from "@/components/drawer/editUserDrawer.vue";
import dayjs from "dayjs";
import MyAlert from "@/components/alert/my-alert.vue";
import ChangePasswordModal from "@/components/modal/changePasswordModal.vue";
const openA = ref(false)
const openE = ref(false)
const showDetail = ref(false)
const openPassword = ref(false)
const asyncLoading = ref(false)
const forms = ref()
const columns = [
  {
    title: '用户账号',
    align: "center",
    dataIndex: 'username',
    width: 100,
    sorter: true
  },
  {
    title: '用户姓名',
    align: "center",
    width: 100,
    dataIndex: 'realname',
  },
  {
    title: '昵称',
    align: "center",
    width: 100,
    dataIndex: 'nickname',
  },
  {
    title: '邮箱',
    align: "center",
    width: 120,
    dataIndex: 'email'
  },
  // {
  //   title: '部门',
  //   align: "center",
  //   width: 120,
  //   dataIndex: 'orgCodeTxt'
  // },
  {
    title: '状态',
    align: "center",
    width: 80,
    dataIndex: 'status'
  },
  {
    title: '创建人',
    align: "center",
    width: 50,
    dataIndex: 'createBy'
  },
  {
    title: '更新人',
    align: "center",
    width: 50,
    dataIndex: 'updateBy'
  },
  {
    title: '更新时间',
    align: "center",
    width: 140,
    dataIndex: 'updateTime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {customRender: 'action'},
    align: "center",
    fixed: 'right',
    width: 140
  }
]
const username = ref('')
const formStateAgent = reactive({
  username: '',
  agentUserName: '',
  startTime: undefined,
  endTime: undefined,
  status: 1,
})
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getUserList,
  queryFactory: () => ({
    status: '',
    columns:'createTime'
  })
})
const selectedRowKeys = ref([])
const item = ref({})
/**
 * 选择项变化
 * @param e
 * @param v
 */
const onSelectChange = (e,v) => {
  selectedRowKeys.value = e
}
/**
 * 清空选中项
 */
const  onClearSelected = () => {
  selectedRowKeys.value = []
}
const formItems = ref([
  {
    label: '用户名',
    field: 'username',
    type: 'input' // 显示的类型，列如input
  },
  {
    label: '真实姓名',
    field: 'realname',
    type: 'input'
  },
  {
    label: '昵称',
    field: 'nickname',
    type: 'input'
  },
  {
    label: '状态',
    field: 'status',
    type: 'select',
    options: [
      { label: '请选择', value: '' },
      { label: '正常', value: '1' },
      { label: '冻结', value: '2' }
    ]
  },
  {
    label: '邮箱',
    field: 'email',
    type: 'input'
  },
])
/**
 * 打开新增用户抽屉
 */
const handleOpen = () => {
  openA.value = true
}
/**
 * 关闭新增用户抽屉
 */
const handleClose = () => {
  openA.value = false
  reset()
}
/**
 * 打开编辑用户抽屉
 */
const handleOpenE = (record) => {
  item.value = Object.assign({selectedroles:[],selecteddeparts:''}, record)
  item.value.post = item.value.post === "" ? [] : item.value.post
  if(item.value.birthday){
    item.value.birthday = dayjs(item.value.birthday)
  }
  openE.value = true
}
/**
 * 关闭编辑用户抽屉
 */
const handleCloseE = () => {
  openE.value = false
  showDetail.value = false
  reset()
}
/**
 * 打开详情抽屉
 * @param record
 */
const detail = (record) => {
  showDetail.value = true
  item.value = Object.assign({selectedroles:[],selecteddeparts:''}, record)
  item.value.post = item.value.post === "" ? [] : item.value.post
  if(item.value.birthday){
    item.value.birthday = dayjs(item.value.birthday)
  }
  openE.value = true
}
/**
 * 单个删除
 * @param record
 * @returns {Promise<void>}
 */
const delOne = async (record) => {
  const res = await deleteOneUser('/sys/user/delete',{id:record.id})
  if(res.success){
    message.success('删除成功')
  }else{
    message.error(res.message)
  }
  await reset()
}
/**
 * 冻结/解冻
 * @param record
 * @returns {Promise<void>}
 */
const freeze = async (record) => {
  const {id, status, username} = record
  //TODO 后台校验管理员角色
  if ('admin' === username) {
    message.warning('管理员账号不允许此操作！');
    return;
  }
  const res = await frozenBatch({ids: id, status: status === 1 ? 2 : 1})
  if (res.success) {
    message.success(res.message);
    reset();
  } else {
    message.warning(res.message);
  }
}
/**
 * 打开更新密码的弹窗
 * @param record
 */
const updatePassword = (record) => {
  openPassword.value = true
  username.value = record.username
}

// const ruleAgent = {
//     agentUserName:[{ required: true, message: '请输入代理人用户名!' }],
//     startTime:[{ required: true, message: '请输入代理开始时间!' }],
//     endTime:[{ required: true, message: '请输入代理结束时间!' }],
// }
// const agent = (record) => {
//   openAgent.value = true
//   formStateAgent.username = record.username
// }

// const onSearch = async () => {
//   const res = await queryByUserName({userName:formStateAgent.username})
//   console.log(res)
// }
//
// const handleAgent = () => {
//   forms.value.validate().then(async() => {
//     console.log(formStateAgent)
//     btnLoading.value = true
//   }).catch(err=>{
//     console.log('err', err)
//     btnLoading.value = false
//   })
// }

/**
 * 关闭更新密码的弹窗
 */
const handleCancelPassword = () => {
  openPassword.value = false
  search()
}
// const handleCancelAgent = () => {
//   openAgent.value = false
//   forms.value.resetFields()
// }
const cancel = () => {
  console.log('cancel')
}

const asyncUser = async () => {
  try{
    asyncLoading.value = true
    const res = await queryUserSync({})
    message.success('同步成功')
    search()
  }catch(err){
    search()
    throw new Error(err)
  }finally {
    asyncLoading.value = false
  }
}

</script>
<style scoped>

</style>
